package fun.stgoder.dev.listener.common;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import fun.stgoder.dev.listener.common.face2.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FaceHttpApi {
    private static Logger logger = LoggerFactory.getLogger(FaceHttpApi.class);

    public static Long findWho(File file) {
        if (file == null || !file.exists()) {
            return 0L;
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("image", file);
        paramMap.put("size", file.length());
        paramMap.put("user_top_num", "1");
        String resp = HttpUtil.post(Constants.FACE_API_URL, paramMap, 1000 * 3);
        logger.debug(resp);
        FaceHttpResp faceHttpResp = JSONUtil.toBean(resp, FaceHttpResp.class);
        if (faceHttpResp.getErrno() == 0) {
            FaceHttpRespData data = faceHttpResp.getData();
            List<FaceHttpRespDataResult> result = data.getResult();
            if (result != null || result.size() > 0) {
                FaceHttpRespDataResult faceHttpRespDataResult = result.get(0);
                float score = Float.parseFloat(faceHttpRespDataResult.getScore());
                if (score >= Constants.FACE_MATCH_SCORE) {
                    Long prisonerId = Long.parseLong(faceHttpRespDataResult.getUser_id());
                    logger.debug("match score: " + score + ", prisonerId: " + prisonerId);
                    return prisonerId;
                }
            }
        }
        return 0L;
    }

    public static String findWho2(File file) {
        long now = System.currentTimeMillis();
        HttpRequest post = HttpUtil.createPost(Constants.FACE2_SERVER_HOST + CommonConstant.FACE_SEARCH_URL);
        String token = CommonUtils.generateToken(Constants.FACE2_APP_KEY, now, Constants.FACE2_APP_SECRET);
        post.header("Accept", "*/*");
        post.header("Token", token);
        post.form("appKey", Constants.FACE2_APP_KEY);
        post.form("timestamp", String.valueOf(now));
        post.form("imageFile", file);
        post.form("resultCount", "1");
        post.form("facesetToken", Constants.FACE2_FACESET_TOKEN);
        post.timeout(30 * 1000);

        String body = post.execute().body();
        logger.debug(body);
        SearchResult result = JSONUtil.toBean(body, SearchResult.class);
        if (result.getStatus() == 0) {
            SearchResultData data = result.getData();
            boolean exists = data.isExists();
            if (exists) {
                List<SearchResultItem> results = data.getResults();
                SearchResultItem item = results.get(0);
                String faceToken = item.getFaceToken();
                float confidence = item.getConfidence();
                if (confidence * 100 >= Constants.FACE_MATCH_SCORE) {
                    return faceToken;
                } else if (Constants.TEST_MODE) {
                    file.renameTo(new File(file.getAbsolutePath() + "_low_score_" + confidence + ".jpg"));
                }
            }
        } else if (Constants.TEST_MODE) {
            file.renameTo(new File(file.getAbsolutePath() + "_face_not_exist.jpg"));
        }
        return null;
    }

    public static void reverse(byte[] arr) {
        if (arr.length < 2)
            return;
        for (int i = 0; i < arr.length / 2; i++) {
            byte b1 = arr[i];
            byte b2 = arr[arr.length - 1 - i];
            arr[i] = b2;
            arr[arr.length - 1 - i] = b1;
        }
    }

    public static void main(String[] args) throws IOException {
        /*Long prisonerId = FaceHttpApi.findWho(new File("C:\\Users\\stgoder\\Desktop\\tmp\\2020-09-16\\5f618539dc27e8b86d1008ec.jpg"));
        System.out.println(prisonerId);*/
        String faceToken = FaceHttpApi.findWho2(new File("C:\\Users\\stgoder\\Desktop\\tmp\\2020-09-16\\5f618539dc27e8b86d1008ec.jpg"));
        logger.info(faceToken);
    }
}
